package kis.io.post;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.xml.sax.InputSource;

public class RequestXml extends HttpServlet
{
	

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		request.setCharacterEncoding("UTF-8");
		System.out.println(request.getCharacterEncoding());
		response.setCharacterEncoding("GBK");
		PrintWriter out = response.getWriter();
		// response.setContentType("text/html;charset=GBK");
		System.out.println(request.getContentLength());
		char[] readerBuffer = new char[request.getContentLength()];
		BufferedReader buffereReader = request.getReader();
		int portion = buffereReader.read(readerBuffer);
		int amount = portion;
		// while (amount < readerBuffer.length)
		// {
		// portion = buffereReader.read(readerBuffer, amount,
		// readerBuffer.length - amount);
		// amount = amount + portion;
		// }
		StringBuffer stringBuffer = new StringBuffer((int) (readerBuffer.length * 1.5));
		for (int index = 0; index < readerBuffer.length; index++)
		{
			char c = readerBuffer[index];
			stringBuffer.append(c);
		}
		String xml = stringBuffer.toString();
		System.out.println(xml);
		StringReader sr = new StringReader(xml.trim());
		try
		{
			Document doc = new SAXBuilder().build(new InputSource(sr));
			Format format = Format.getPrettyFormat();
			format.setEncoding("GBK");
			XMLOutputter putter = new XMLOutputter(format);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd24HHmmssSSS");
			String path = this.getClass().getResource("/").toString().replace("file:", "") + sdf.format(new Date()) + ".xml";
			putter.output(doc, new FileOutputStream(path));
			//读取xml数据
		} catch (JDOMException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.println("sss");
	}

	public static String replaceBlank(String str)
	{
		String dest = "";
		if (str != null)
		{
			Pattern p = Pattern.compile("\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}
}
